<?php
namespace App\Http\Controllers\Wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Yunpian\Sdk\YunpianClient;
use App\Repos\UserRepo;
use App\Services\RedisService;
use App\Models\Product;
use App\Models\Cate;
use App\Models\Notice;
use App\Models\Banner;
use App\Models\Coupon;
use EasyWeChat;
use Log;

class IndexController extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $app = app('wechat.official_account');
        //dd($app);
        $app->server->push(function($message){
         
            //return "欢迎关注!业务问题请加微信 bzs1984 咨询，谢谢。";        
           return env('WELCOME_MSG', '欢迎关注!');
            
        });

        return $app->server->serve();
    }

    // 返回openid    
    public function getOpenid(Request $request)
    {
        $rs['status'] = false;
        $code = trim($request->code);
        $mini = EasyWeChat::miniProgram(); // 小程序
        $result = $mini->auth->session($code); // $code 为wx.login里的code
        if(!array_key_exists('openid', $result)) {
            $rs['msg'] = $result['errmsg'];
            return response()->json($rs);
        }
        $rs['status'] = true;
        $rs['openid']      = $result['openid'];
        $rs['session_key'] = $result['session_key'];
        return response()->json($rs);
    }

    /**
     * 获取微信用户信息，主要是unionid
     */
    public function getWxUser(Request $request)
    {
        $rs['status'] = false;      
        $session     = $request->session_key;
        $iv          = $request->iv;
        $encryptData = $request->encryptData;
        $app         = EasyWeChat::miniProgram(); // 小程序
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptData);
        if($decryptedData) {
            $rs['status'] = true;
            $rs['data'] = $decryptedData;            
            return response()->json($rs);
        }
        return response()->json($rs);
    }
   
    // 小程序验证身份获取token
    public function getToken(Request $request)
    {
        $rs['status'] = true;
        $data = array_only($request->all(),['longitude','latitude','avatar','nickname','name','mobile','unionid','small_openid']);
      
        $user = UserRepo::create($data);
        $rs['data']['token']   = $user->token;
        $rs['data']['user_id'] = $user->id;
        return response()->json($rs);   
    }

    
   

    public function cate(Request $request)
    {
        $rs['status']     = true;
       
        $list = Cate::select(['id','name'])
                                    ->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    public function upload(Request $request)
    {
        $rs['status'] = true;
        $folder       = 'uploads/'.date('Ymd');
        
        if ($request->isMethod('post')) {
            $file = $request->file('file');

            // 文件是否上传成功
            if ($file->isValid()) {                
                $path = '/'.$file->store($folder);                    
                
                $rs['data'] = $path;
                return response()->json($rs);
            }

        }
        return response()->json(['rs' => false, 'msg' => '不是正确请求方式']);
    }


    public function notice(Request $request)
    {
        $rs['status'] = true;       
        $data = Notice::orderBy('weight','asc')->get();
        $rs['data'] = $data;
        return response()->json($rs);
    }

    /**
     * 首页推荐的分类
     */
    public function recCate(Request $request)
    {
        $rs['status']     = true;       
        $list = Cate::select(['id','name','thumb'])
                        ->orderBy('weight','asc')
                        ->take(6)->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    /**
     * 首页推荐的商品
     */
    public function recProduct(Request $request)
    {
        $rs['status']     = true;
        $where['status'] = 1;
        $where['is_rec'] = 1;
        $list = Product::where($where)
                        ->take(12)
                        ->orderBy('price','asc')
                        ->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }


     /**
     * 首页往期的商品
     */
    public function oldProduct(Request $request)
    {
        $rs['status']     = true;
       
        $where['status'] = 2; // 已下架商品
        $list = Product::where($where)
                        ->take(12)
                        ->orderBy('created_at','desc')
                        ->get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    public function banner(Request $request)
    {
        $rs['status'] = true;       
        $list = Banner::get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    public function coupon(Request $request)
    {
        $rs['status'] = true;
        $list = Coupon::get();
        $rs['data'] = $list;
        return response()->json($rs);
    }

    public function getSmallcode(Request $request)
    {   // scene_value = '20-2';  商品id,用户id ; id, agent_id
        $value = explode('-', $request->scene_value);

        $app = EasyWeChat::miniProgram(); // 小程序
        //$page = 'pages/productDetails/productDetails?id='.$value[0].'&agent_id='.$value[1];
        $page = 'pages/productDetails/productDetails';
         
        $response = $app->app_code->getUnlimit($request->scene_value, [
            'page'  => $page,
            'width' => 300,
            
        ]);
      
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save('uploads/smallcode', $request->scene_value.'.png');
            $rs['status'] = true;
            $rs['data'] = '/uploads/smallcode/'.$filename;
            return response()->json($rs);
        }
    }
   


    
}
